package com.prizedraw.prize_draw.security;

import com.prizedraw.prize_draw.entity.SysUser;
import com.prizedraw.prize_draw.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    SysUserService sysUserService;

    /**
     * 查询用户登录
     * @param userId
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        //让其根据用户的工号进行查询  user_id为工号，这名称起得有点毛病，和本身的id有点冲突，早知道叫empno
        SysUser user = sysUserService.getByUserId(userId);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码不正确");
        }
        return new AccountUser(user.getUserId(), user.getUserName(),user.getPassowrd(), getUserAuthority(user.getId()));
    }

    /**
     * 获取用户权限信息（角色、菜单权限）
     * @param userId
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(Integer userId) {
        String authority = sysUserService.getUserAuthorityInfo(userId);  // ROLE_admin,ROLE_normal,sys:user:list,....1
//        log.info("用户 -- {} 权限 -- {}", SecurityContextHolder.getContext().getAuthentication().getPrincipal(), authority);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }

}
